package dynamic

import "encoding/json"

//https://www.zhihu.com/question/589384628/answer/2998995526
//GO 编程如何动态添加 struct 字段？ （JSON 解析相关）

type User struct {
	Name string
	Age  int
	Attr map[string]interface{}
}

func (u *User) UnmarshalJSON(data []byte) error {
	var datas map[string]interface{}
	if err := json.Unmarshal(data, &datas); err != nil {
		return err
	}
	if name, ok := datas["name"]; ok {
		u.Name = name.(string)
		delete(datas, "name")
	}
	if age, ok := datas["age"]; ok {
		u.Age = int(age.(float64))
		delete(datas, "age")
	}
	u.Attr = datas
	return nil
}

func (u *User) MarshalJSON() ([]byte, error) {
	datas := make(map[string]interface{})
	datas["name"] = u.Name
	datas["age"] = u.Age
	for k, v := range u.Attr {
		datas[k] = v
	}
	return json.Marshal(datas)
}
